package com.bonc.cq.cloud.controller;
import com.alibaba.fastjson.JSONObject;
import com.bonc.cq.cloud.feign.InstanceFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/instanceRibbon")
public class InstanceRibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${server.port}")
    private String port;

    @GetMapping("/getInstance/{serviceId}")
    @HystrixCommand(fallbackMethod = "getInstanceFallback")
    public JSONObject getInstance(@PathVariable String serviceId){
        JSONObject json = restTemplate.getForObject("http://provider-server/instance/getInstance/"+serviceId,JSONObject.class);
        json.put("consumer port",port);
        return json;
    }

    /**
     * 熔断方法
     */
    public JSONObject getInstanceFallback(String serviceId) {
        JSONObject fallback = new JSONObject();
        fallback.put("detail", "服务调用发生异常");
        fallback.put("serviceId", serviceId);
        fallback.put("consumer port",port);
        return fallback;
    }
}
